/*
 * @Author: liu wang wang
 * @Date: 2020-07-14 13:51:23
 * @LastEditTime: 2020-07-17 17:40:03
 * @LastEditors: liu wang wang
 * @Description: Form表单数据处理 
 * @FilePath: \st-sdk-js\src\utils\formdata.ts
 */
import { serialization, isArray } from '../tools';
import { limit } from './checkboxLimit';
// 获取表单数据
export function getFormData(formID: string): any {
    const editForm: HTMLElement | null = document.getElementById(formID);
    const inputCollection: HTMLCollection = (editForm as HTMLElement).getElementsByTagName('input');
    const selectCollection: HTMLCollection = (editForm as HTMLElement).getElementsByTagName('select');
    const formCollection = Array.prototype.slice.call(inputCollection).concat(Array.prototype.slice.call(selectCollection));
    const formData = serialization(formCollection);
    for (const key in formData) {
        if (formData.hasOwnProperty(key)) {
            if (isArray(formData[key])) {
                formData[key] = formData[key].join();
            }
        }
    }
    return formData;
}

// 设置表单数据
export function setFormData(formID: string, res: any): void {
    (document.getElementsByName('versionName')[0] as HTMLInputElement).value = res.versionName;
    setSelect('occupationNum',res.occupationNum);
    setSelect('versionType',res.versionType);
    setCheckBox('terminalType',res.terminalType);
    setCheckBox('characteristic',res.characteristic);
    setCheckBox('others',res.others);
    limit('characteristic',3);
    limit('others',3);
    // 设置复选框
    function setCheckBox(name: string, value: string){
        const checks:NodeListOf<HTMLElement> = document.getElementsByName(name);
        const valueArray:string[] = value.split(',');
        Array.prototype.forEach.call(checks, function (option) {
            if (valueArray.indexOf(option.value)>=0) {
                option.checked = true;
            }
        });
    }
    // 设置下拉框
    function setSelect(name: string, value: number) {
        const selectOptions = document.getElementsByName(name)[0].getElementsByTagName('option');
        Array.prototype.forEach.call(selectOptions, function (option) {
            if (option.value == value) {
                option.selected = true;
            }
        });
    }
}

// 格式化多选框数据格式
export function transformCheckbox(val: any, inputName: string): any {
    return val.map(({ id, name }: { id: number, name: string }) => {
        return {
            value: id,
            id: name + id,
            text: name,
            name: inputName
        }
    });
}